package com.atguigu.gmall.auth.service.impl;

import com.atguigu.gmall.auth.config.JwtProperties;
import com.atguigu.gmall.auth.feign.GmallUmsClient;
import com.atguigu.gmall.auth.service.AuthService;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.exception.GmallUserException;
import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.IpUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import com.atguigu.gmall.ums.entity.UserEntity;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@EnableConfigurationProperties(JwtProperties.class)
@Service
public class AuthServiceImpl implements AuthService {
    @Resource
    GmallUmsClient gmallUmsClient;
    @Resource
    JwtProperties jwtProperties;
    @Override
    public void login(String loginName, String password,HttpServletRequest request,
                      HttpServletResponse response) {
        //1、根据登录账号密码 访问ums服务查询用户数据
        ResponseVo<UserEntity> userEntityResponseVo = gmallUmsClient.queryUser(loginName, password);
        UserEntity userEntity = userEntityResponseVo.getData();
        if(userEntity==null){
            //查询失败
            throw new GmallUserException(userEntityResponseVo.getMsg(),
                    userEntityResponseVo.getCode());
        }
        try {
            //登录成功
            //2、查询成功代表登录成功：构建jwt token字符串
            Map<String, Object> map = new HashMap<>();
            map.put("userId" , userEntity.getId());
            map.put("userName" , userEntity.getUsername());
            //获取客户端ip设置到map中
            String ip = IpUtils.getIpAddressAtService(request);
            map.put("ip",ip);
            //将jwt需要的公钥私钥+jwt的过期时间等配置 抽取到一个配置类中管理
            //获取privateKey：
            String token = JwtUtils.generateToken(map, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            //3、将token作为cookie设置到浏览器响应报文中
            //表示用户登录成功的状态
            CookieUtils.setCookie(request,response,jwtProperties.getCookieName(),token,
                    jwtProperties.getExpire()*60);
            //unick:表示前端登录成功回显用户昵称的cookie
            CookieUtils.setCookie(request,response,jwtProperties.getUnickCookieName(),
                    userEntity.getNickname(),
                    jwtProperties.getExpire()*60);
        } catch (Exception e) {
            throw new GmallUserException("登录失败",
                    6);
        }
    }
}
